import { createStore } from "vuex";

import { isRegister, toLogin } from "../utils/app";

import { Toast } from "vant";

export default createStore({
  state: {
    loginData: [],
    loginState: false,
  },
  mutations: {
    getUserData(state, payload) {
      state.loginData = payload.list;
      state.loginState = true;
      console.log(state.loginData);
      localStorage.setItem("token", state.loginData._id);
      localStorage.setItem("gather", JSON.stringify(state.loginData.gather));

      console.log(state.loginState);
    },

    addUserInfo(state, payload) {
      console.log(5678);
      state.loginData = payload.list;
      state.loginState = true;
      console.log(state.loginData);
      localStorage.setItem("token", state.loginData[0]._id);
      localStorage.setItem("gather", JSON.stringify(state.loginData[0].gather));
    },

    changeLoginState(state) {
      state.loginState = false;
    },
  },
  actions: {
    async getUserDataAsync({ commit }, tel) {
      const res = await isRegister({
        phone: tel,
      });
      console.log(res);
      if (res.list) {
        commit("getUserData", res);
        Toast.success(tel + "用户，好久不久");
      } else {
        Toast.success("第一次注册，可以享受新手福利");
      }
    },

    async addUserInfoAsync({ commit }, tel) {
      const res = await toLogin({
        phone: tel,
      });
      commit("addUserInfo", res);
    },
  },
  modules: {},
});
